package config

import (
	"go-chat/utils"
	"log"
	"os"
	"strings"

	"github.com/joho/godotenv"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// 定义配置类
type Config struct {
	ServerIP   string //服务器ip
	DBPassWord string //数据库密码
	DBUserName string //数据库用户名
	DBName     string //数据库名称
}

var (
	DB *gorm.DB
)

func Init() {
	conf := LoadConfig()
	LoadDBConf(conf) //加载数据库
}

func LoadConfig() *Config {
	godotenv.Load() //加载.env文件
	return &Config{
		ServerIP:   os.Getenv("SERVER_IP"),
		DBPassWord: os.Getenv("DB_PASSWORD"),
		DBUserName: os.Getenv("DB_USERNAME"),
		DBName:     os.Getenv("DB_NAME"),
	}
}

// 对数据库进行配置
func LoadDBConf(conf *Config) {
	dsn := strings.Join([]string{
		conf.DBUserName, ":",
		conf.DBPassWord,
		"@tcp(", conf.ServerIP, ":3306", ")/",
		conf.DBName, "?charset=utf8&parseTime=true"}, "")
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("数据库连接失败：", err)
	}

	DB = db //赋值给全局变量
	utils.PrintTables(db)
}

func LoadMongoDBConf(conf *Config) {

}

func LoadRedisConf(conf *Config) {

}
